package com.gxgeek.javabasic.lru;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by GX on 2017/8/31.
 */
public class LRUCacheByLinkedHashMap<K, V> extends LinkedHashMap<K,V> implements Serializable{

    private static final long serialVersionUID = -7239870434232142730L;
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;
    private int maxSize;

    public LRUCacheByLinkedHashMap(int maxSize) {
        super((int) Math.ceil(maxSize/DEFAULT_LOAD_FACTOR)+1,DEFAULT_LOAD_FACTOR,true);
        this.maxSize = maxSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size()>this.maxSize;
    }

    public static void main(String[] args) {
        LRUCacheByLinkedHashMap<String,     String> c = new LRUCacheByLinkedHashMap<>(3);
        c.put("1", "one"); // 1
        c.put("2", "two"); // 2 1
        c.put("3", "three"); // 3 2 1
        c.put("4", "four"); // 4 3 2
        if (c.get("2") == null)
            throw new Error(); // 2 4 3
        c.put("5", "five"); // 5 2 4
        c.put("4", "second four"); // 4 5 2
        // Verify cache content.
        if (c.size() != 3)
            throw new Error();
        if (!c.get("4").equals("second four"))
            throw new Error();
        if (!c.get("5").equals("five"))
            throw new Error();
        if (!c.get("2").equals("two"))
            throw new Error();
        // list cache content.
        for (Map.Entry<String, String> entry : c.entrySet()){
            System.out.println("key:"+entry.getKey()+"      value:"+entry.getValue());
//            System.out.println(entry.getValue());

        }

    }

}
